using System;
using System.Collections;
using System.Data;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using eWorld.UI;
using TimeSheet.Logger;
using TimeSheetBLL;

namespace TimeSheet.view
{
    /// <summary>
    ///		Summary description for DefaultView.
    /// </summary>
    public abstract class DefaultView : TimeSheetControl
    {
        protected Label lblMessage;
        protected Button btnAddChargeableHours;
        protected Button btnAddNonChargeableHours;
        protected Label Label1;
        protected Label Label2;
        protected DataGrid dgChargeable;
        protected DataGrid dgNonChargeable;
        protected DropDownList ddlActivities;
        protected Label lblSummary;
        protected Label lblTotal;
        protected Label lblChargeable;
        protected Label lblNonChargeable;
        protected Label lblVariance;
        protected Label lblPayPeriodPlaceholder;
        protected HtmlTableCell summaryCell;
        protected Calendar calTimesheet;
        protected NumericBox txtChargeableHours;
        protected MultiTextDropDownList ddlProjects;
        protected NumericBox txtNonChargeableHours;
        protected Label lblNonBillableErr;
        protected Label lblBillableErr;
        protected CheckBox cbShowAll;
        protected TextBox txtNonBillableComments;
        protected TextBox txtBillableComments;

        private void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                calTimesheet.SelectedDate = DateTime.Now;
                lblSummary.Text = calTimesheet.SelectedDate.ToShortDateString();
                LoadForm();
                LoadDropDowns();
            }
        }

        private void LoadForm()
        {
            User user = GetUser();
            DateTime date = calTimesheet.SelectedDate;

            DataTable chargeable = user.GetChargeableHoursByPayPeriod(date);
            //get the user from the session
            dgChargeable.DataSource = chargeable;

            DataTable nonChargeable = user.GetNonChargeableHoursByPayPeriod(date);
            //get the user from the session
            dgNonChargeable.DataSource = nonChargeable;

            dgChargeable.DataBind();
            dgNonChargeable.DataBind();

            CalculateSummary(chargeable, nonChargeable);
            CalculatePeriodSummary(calTimesheet.SelectedDate);
        }

        private void LoadDropDowns()
        {
            ddlActivities.DataSource =
                BrokerFactory.GetBroker(new Activity()).SelectAll(null);
            ddlActivities.DataTextField = "activity_name";
            ddlActivities.DataValueField = "activity_id";
            ddlActivities.DataBind();

            if (cbShowAll.Checked)
            {
                LoadAllProjects();
            }
            else
            {
                LoadRecentProjects();
            }
        }

        private void LoadRecentProjects()
        {
            User user = (User) Session["User"];
            ddlProjects.DataSource = user.GetRecentProjects();
            ddlProjects.DataTextFields = "client_name, project_name";
            ddlProjects.DataTextFormatString = "{0} - {1}";
            ddlProjects.DataValueField = "project_id";
            ddlProjects.DataBind();
        }

        private void LoadAllProjects()
        {
            ddlProjects.DataSource = Project.GetAllStaffVisibleProjects();
            ddlProjects.DataTextFields = "client_name, project_name";
            ddlProjects.DataTextFormatString = "{0} - {1}";
            ddlProjects.DataValueField = "project_id";
            ddlProjects.DataBind();
        }

        private void CalculatePeriodSummary(DateTime date)
        {
            DateTime perStart = Utils.GetPayPeriodStart(date);
            DateTime perEnd = Utils.GetPayPeriodEnd(date);

            HtmlTable table = new HtmlTable();
            table.Attributes.Add("width", "100%");
            User user = GetUser();
            Hashtable ht = user.GetUserHoursByPayPeriod(date);

            while (perStart.Day <
                   perEnd.Day)
            {
                HtmlTableRow row = GetSummaryRow(perStart, ht);
                if (row != null)
                {
                    table.Rows.Add(row);
                }
                perStart = perStart.AddDays(1);
            }

            HtmlTableRow lastRow = GetSummaryRow(perStart, ht);
            if (lastRow != null)
            {
                table.Rows.Add(lastRow);
            }

            summaryCell.Controls.Add(table);
        }

        private HtmlTableRow GetSummaryRow(DateTime date, Hashtable dailyHoursList)
        {
            DailyHours dh = dailyHoursList[date] as DailyHours;

            HtmlTableCell leftCell = new HtmlTableCell();
            HtmlTableCell rightCell = new HtmlTableCell();
            HtmlTableRow row = new HtmlTableRow();

            if (dh == null)
            {
                if (date.DayOfWeek != DayOfWeek.Saturday &&
                    date.DayOfWeek != DayOfWeek.Sunday)
                {
                    leftCell.InnerHtml = "<span id=\"summarytext\">" +
                                         date.DayOfWeek + ", " +
                                         date.Day + ": </span>";
                    rightCell.InnerHtml =
                        "<div class=\"below\"><img src=\"images/xclock.gif\">-7.5</div>";

                    row.Cells.Add(leftCell);
                    row.Cells.Add(rightCell);
                }
                else
                {
                    return null;
                }
            }
            else
            {
                double variance = dh.GetVariance();

                leftCell.InnerHtml = "<span id=\"summarytext\">" +
                                     date.DayOfWeek + ", " +
                                     date.Day + ": </span>";
                if (variance > 0)
                {
                    rightCell.InnerHtml =
                        "<div class=\"above\"><img src=\"images/button_ok.gif\"></div>";
                }
                else if (variance < 0)
                {
                    rightCell.InnerHtml =
                        "<div class=\"below\"><img src=\"images/xclock.gif\">" +
                        variance + "</div>";
                }
                else
                {
                    rightCell.InnerHtml =
                        "<div class=\"even\"><img src=\"images/button_ok.gif\"></div>";
                }

                row.Cells.Add(leftCell);
                row.Cells.Add(rightCell);
            }

            return row;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="chargeable"></param>
        /// <param name="nonChargeable"></param>
        private void CalculateSummary(DataTable chargeable, DataTable nonChargeable)
        {
            double chargeHours = 0;
            double nonChargeHours = 0;

            foreach (DataRow row in chargeable.Rows)
            {
                double h = Convert.ToDouble(row["charge_hours"]);
                chargeHours += h;
            }

            foreach (DataRow row in nonChargeable.Rows)
            {
                double h = Convert.ToDouble(row["non_charge_hours"]);
                nonChargeHours += h;
            }

            double total = chargeHours + nonChargeHours;
            double variance = total - 7.5;

            lblChargeable.Text = chargeHours.ToString();
            lblNonChargeable.Text = nonChargeHours.ToString();
            lblTotal.Text = total.ToString();

            if (variance > 0)
            {
                lblVariance.Text = "<div class=\"above\">+" + variance.ToString() +
                                   "</font>";
            }
            else if (variance < 0)
            {
                lblVariance.Text = "<div class=\"below\">" + variance.ToString() +
                                   "</font>";
            }
            else
            {
                lblVariance.Text = variance.ToString();
            }
        }

        private void SetFormControls(bool readOnly)
        {
            //check to see if the lock on dates outside of the current pay period exists
            if (!AppSettings.IsLocked)
            {
                readOnly = true;
            }
            txtChargeableHours.Enabled = readOnly;
            txtNonChargeableHours.Enabled = readOnly;
            ddlActivities.Enabled = readOnly;
            ddlProjects.Enabled = readOnly;
            btnAddChargeableHours.Enabled = readOnly;
            btnAddNonChargeableHours.Enabled = readOnly;
        }

        #region Web Form Designer generated code

        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        ///		Required method for Designer support - do not modify
        ///		the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.calTimesheet.SelectionChanged +=
                new System.EventHandler(this.calTimesheet_SelectionChangedEvent);
            this.cbShowAll.CheckedChanged +=
                new System.EventHandler(this.cbShowAll_CheckedChanged);
            this.btnAddChargeableHours.Click +=
                new System.EventHandler(this.btnAddChargeableHours_Click);
            this.dgChargeable.DeleteCommand +=
                new System.Web.UI.WebControls.DataGridCommandEventHandler(
                    this.OnChargeableDeleted);
            this.btnAddNonChargeableHours.Click +=
                new System.EventHandler(this.btnAddNonChargeableHours_Click);
            this.dgNonChargeable.DeleteCommand +=
                new System.Web.UI.WebControls.DataGridCommandEventHandler(
                    this.OnNonChargeableDeleted);
            this.Load += new System.EventHandler(this.Page_Load);
        }

        #endregion

        private void calTimesheet_SelectionChangedEvent(object sender, EventArgs e)
        {
            DateTime perStart = DateTime.Now.AddDays(AppSettings.PastDateLockSeed);
            DateTime perEnd = DateTime.Now.AddDays(AppSettings.FutureDateLockSeed);
            DateTime currDate = calTimesheet.SelectedDate;
            bool enableControls = false;

            //check to see if the user is able to enter their hours for the selected date.
            if (currDate >= perStart &&
                currDate <= perEnd)
            {
                enableControls = true;
            }

            SetFormControls(enableControls);

            LoadForm();
            lblSummary.Text = calTimesheet.SelectedDate.ToShortDateString();
        }

        private void btnAddChargeableHours_Click(object sender, EventArgs e)
        {
            ChargeableHours ch = new ChargeableHours();
            try
            {
                lblBillableErr.Text = "";
                lblNonBillableErr.Text = "";
                ch.ChargeDate = calTimesheet.SelectedDate;
                ch.ChargeHours = Convert.ToDouble(txtChargeableHours.Text);
                ch.UserID = GetUser().ID;
                ch.ProjectID = Convert.ToInt32(ddlProjects.SelectedItem.Value);
                if (txtBillableComments.Text.Length > 0)
                {
                    ch.Comments = txtBillableComments.Text;
                }
                BrokerFactory.Save(ch);
                LoadForm();
                txtChargeableHours.Text = "";
                txtBillableComments.Text = "";
            }
            catch (FormatException)
            {
                lblBillableErr.Text = AppSettings.InputErrorMessage;
            }
            catch (Exception ex)
            {
                lblBillableErr.Text = AppSettings.InputErrorMessage;
                ExceptionLogger.AddException(ex);
            }
        }

        private void btnAddNonChargeableHours_Click(object sender, EventArgs e)
        {
            NonChargeableHours nch = new NonChargeableHours();
            try
            {
                lblBillableErr.Text = "";
                lblNonBillableErr.Text = "";
                nch.NonChargeDate = calTimesheet.SelectedDate;
                nch.NonChargeHours = Convert.ToDouble(txtNonChargeableHours.Text);
                nch.UserID = GetUser().ID;
                nch.ActivityID = Convert.ToInt32(ddlActivities.SelectedItem.Value);
                if (txtNonBillableComments.Text.Length > 0)
                {
                    nch.Comments = txtNonBillableComments.Text;
                }
                BrokerFactory.Save(nch);
                LoadForm();
                txtNonChargeableHours.Text = "";
                txtNonBillableComments.Text = "";
            }
            catch (FormatException)
            {
                lblNonBillableErr.Text = AppSettings.InputErrorMessage;
            }
            catch (Exception ex)
            {
                lblNonBillableErr.Text = AppSettings.InputErrorMessage;
                ExceptionLogger.AddException(ex);
            }
        }

        private void OnChargeableDeleted(
            object source, DataGridCommandEventArgs e)
        {
            try
            {
                ChargeableHours ch = new ChargeableHours();
                ch.ID = Convert.ToInt64(e.Item.Cells[0].Text);
                BrokerFactory.Delete(ch);
                LoadForm();
            }
            catch (Exception ex)
            {
                ExceptionLogger.AddException(ex);
            }
        }

        private void OnNonChargeableDeleted(
            object source, DataGridCommandEventArgs e)
        {
            try
            {
                NonChargeableHours nch = new NonChargeableHours();
                nch.ID = Convert.ToInt64(e.Item.Cells[0].Text);
                BrokerFactory.Delete(nch);
                LoadForm();
            }
            catch (Exception ex)
            {
                ExceptionLogger.AddException(ex);
            }
        }

        private void cbShowAll_CheckedChanged(object sender, EventArgs e)
        {
            CalculatePeriodSummary(calTimesheet.SelectedDate);
            LoadDropDowns();
        }
    } //class
} //namespace